package com.lagou.controller;

import com.lagou.pojo.Token;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable("email") String email,@PathVariable("password") String password,@PathVariable("code") String code, HttpSession session){
        boolean result = userService.registerUser(email, password, code);
        if(result){
            Token tokenObject = userService.loginUser(email, password);

            session.setAttribute("token",tokenObject.getToken());
        }
        return result;
    }

    @PostMapping("/login/{email}/{password}")
    public boolean login(@PathVariable("email") String email, @PathVariable("password") String password, @SessionAttribute(value = "token",required = false) String token , HttpSession session){
        Token tokenObject = userService.loginUser(email, password);

        if(tokenObject == null){
            throw new RuntimeException("email or password fail,email:" + email + ",password:" + password);
        }

        session.setAttribute("token",tokenObject.getToken());

        return true;
    }

    @GetMapping("/info")
    public String info(@SessionAttribute(value = "token",required = false) String token){
        String email = userService.getEmailByToken(token);

        return email;
    }

}
